package com.itbac.springsecurityoauth2demo.config;

import com.itbac.springsecurityoauth2demo.service.SmartClientDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.builders.ClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.builders.InMemoryClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;

import javax.annotation.Resource;

/**
 * 线上，授权服务和资源服务是分开的
 * 认证授权服务配置类
 * @author: BacHe
 * @email: 1218585258@qq.com
 * @Date: 2021/3/27 11:44
 */
@Configuration
//启动配置  授权服务
@EnableAuthorizationServer
public class AuthorizationServiceConfig extends AuthorizationServerConfigurerAdapter {
    //加密器
    @Autowired
    private PasswordEncoder passwordEncoder;
    //认证管理器
    @Autowired
    private AuthenticationManager authenticationManager;

    //token保存到Redis中
//    @Resource(name = "redisTokenStore")
//    private TokenStore redisTokenStore;

    //token不用保存在Redis中，而是使用Jwt
//    @Resource(name = "jwtTokenStore")
//    private TokenStore jwtTokenStore;

    //内存保存token
    @Resource(name = "inMemoryTokenStore")
    private TokenStore inMemoryTokenStore;


    //客户端详情服务
    // 查询 clientId 和 secret 的服务
    @Autowired
    private SmartClientDetailsService smartClientDetailsService;


    //配置客户端详细信息服务
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        //基于数据库查询的
        clients.withClientDetails(smartClientDetailsService);

        //基于本地内存的
//        ClientDetailsServiceBuilder<InMemoryClientDetailsServiceBuilder>.ClientBuilder
//                clientBuilder = clients.inMemory()
//                //客户端ID （授权中心颁发的）
//                .withClient("admin")
//                //秘钥 （授权中心颁发的）
//                .secret(passwordEncoder.encode("123456a"))
//                //重定向地址 ,（把授权码code给别人）
//                .redirectUris("http://www.baidu.com")
////                .redirectUris("http://localhost:8081/login")
//                //设置token的失效时间  2小时
//                .accessTokenValiditySeconds(60 * 60 * 2)
//                //refresh_token 的失效时间 24小时
//                .refreshTokenValiditySeconds(60 * 60 * 24)
//                //授权范围
//                .scopes("all")
//                //资源列表
//                .resourceIds("res1")
//                //true，单点登录，自动授权 。false 跳转到授权页面，需要用户点击授权。
//                .autoApprove(true)
//                //授权模式 5 种
//                //authorization_code ：授权码模式
//                //password 密码模式
//                //refresh_token 刷新令牌
//                //client_credentials 客户端模式
//                //implicit 简要模式
//                .authorizedGrantTypes("authorization_code", "password", "refresh_token","client_credentials","implicit");

    }


  /**
   * 令牌服务,描述令牌的特性
   */
    @Bean
    public AuthorizationServerTokenServices tokenServices(){
        DefaultTokenServices services = new DefaultTokenServices();
        //客户端信息服务
        services.setClientDetailsService(smartClientDetailsService);
        //支持刷新token
        services.setSupportRefreshToken(true);
        //令牌存储策略
        services.setTokenStore(inMemoryTokenStore);
        //令牌默认有效期 2小时
        services.setAccessTokenValiditySeconds(60*60*2);
        //刷新令牌默认有效期 3天
        services.setRefreshTokenValiditySeconds(60*60*24*3);
        return services;
    }

    /**
     * 配置令牌访问端点,也就是 url地址。
     * 配置令牌服务
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                //密码模式需要,认证管理器
                .authenticationManager(authenticationManager)
                //授权码服务
                .authorizationCodeServices(authorizationCodeServices())
                //令牌服务
                .tokenServices(tokenServices())
                //允许post请求 访问 端点
                .allowedTokenEndpointRequestMethods(HttpMethod.POST)
        ;

    }
    //令牌访问端点的安全策略,安全约束
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
               //     /oauth/token_key 公开
                .tokenKeyAccess("permitAll()")
                //   /oauth/check_token 公开
                .checkTokenAccess("permitAll()")
                // 允许表单认证,申请令牌
                .allowFormAuthenticationForClients();
    }
    //授权码服务
    @Bean
    public AuthorizationCodeServices authorizationCodeServices(){
        //设置授权码模式的授权码
        return new InMemoryAuthorizationCodeServices();
    }

}
